package com.mvp.shq.washer.view.widget.addressPicker;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.MyViewPagerAdapter;
import com.mvp.shq.washer.adapter.ShopSpecAdapter;
import com.mvp.shq.washer.entity.result.BaseResult;
import com.mvp.shq.washer.entity.shop.ShopSpec;
import com.mvp.shq.washer.entity.shop.address.AreaData;
import com.mvp.shq.washer.entity.shop.address.CityData;
import com.mvp.shq.washer.entity.shop.address.ProvinceData;
import com.mvp.shq.washer.entity.shop.address.UnitData;
import com.mvp.shq.washer.http.RxSchedulers;
import com.mvp.shq.washer.http.ShopApi;
import com.mvp.shq.washer.http.ShopApiService;
import com.mvp.shq.washer.ui.shop.category.CategoryActivity;
import com.mvp.shq.washer.ui.shop.categoryPage.CategoryFragment;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.T;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by shq1 on 2017/10/9.
 */

public class AddressPicker extends PopupWindow {

    private View mPopView;
    private Activity activity;
    private Context context;
    private ImageView imgClose;
    private TabLayout tabLayout;
    private RecyclerView recyclerView1,recyclerView2,recyclerView3,recyclerView4;
    private RecyclerView[] recyclerViews;
    private List<ProvinceData> dataList;
    private AddressPickerAdapter adapter1,adapter2,adapter3,adapter4;
    private AddressPickerAdapter.OnItemClickListener listener1,listener2,listener3,listener4;
    private int pIndex,cIndex,aIndex,uIndex;
    private List<ProvinceData> provinces;
    private List<CityData> citys;
    private List<AreaData> areas;
    private List<UnitData> units;
    private OnAddressPickListener listener;
    private String token;
    public AddressPicker(Context context,Activity mActivity,List<ProvinceData> datas) {
        super(context);
        activity = mActivity;
        this.context = context;
        dataList = datas;
        token = SpUtil.getToken();
        // TODO Auto-generated constructor stub
        init(context);
        setPopupWindow();
    }

    /**
     * 初始化
     *
     * @param context
     */
    @SuppressLint("WrongViewCast")
    private void init(Context context) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = LayoutInflater.from(context);
        //绑定布局
        mPopView = inflater.inflate(R.layout.pop_pick_address, null);
        imgClose = (ImageView)mPopView.findViewById(R.id.img_close);
        tabLayout = (TabLayout)mPopView.findViewById(R.id.tablayout);
        recyclerView1 = (RecyclerView)mPopView.findViewById(R.id.recyclerview1);
        recyclerView2 = (RecyclerView)mPopView.findViewById(R.id.recyclerview2);
        recyclerView3 = (RecyclerView)mPopView.findViewById(R.id.recyclerview3);
        recyclerView4 = (RecyclerView)mPopView.findViewById(R.id.recyclerview4);
        TabLayout.Tab tab1 = tabLayout.newTab();
        tab1.setText("省");
        TabLayout.Tab tab2 = tabLayout.newTab();
        tab2.setText("市");
        TabLayout.Tab tab3 = tabLayout.newTab();
        tab3.setText("区");
        TabLayout.Tab tab4 = tabLayout.newTab();
        tab4.setText("单位");
        tabLayout.addTab(tab1);
        tabLayout.addTab(tab2);
        tabLayout.addTab(tab3);
        tabLayout.addTab(tab4);
        recyclerView1.setLayoutManager(new LinearLayoutManager(context));
        recyclerView2.setLayoutManager(new LinearLayoutManager(context));
        recyclerView3.setLayoutManager(new LinearLayoutManager(context));
        recyclerView4.setLayoutManager(new LinearLayoutManager(context));
        RecyclerViewDivider divider = new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL, 2, ContextCompat.getColor(context,R.color.shop_divison_bg));
        recyclerView1.addItemDecoration(divider);
        recyclerView2.addItemDecoration(divider);
        recyclerView3.addItemDecoration(divider);
        recyclerView4.addItemDecoration(divider);

        adapter1 = new AddressPickerAdapter(context,0);
        provinces = new ArrayList<>();
        adapter1.setProvinces(provinces);
        adapter2 = new AddressPickerAdapter(context,1);
        citys = new ArrayList<>();
        adapter2.setCitys(citys);
        adapter3 = new AddressPickerAdapter(context,2);
        areas = new ArrayList<>();
        adapter3.setAreas(areas);
        adapter4 = new AddressPickerAdapter(context,3);
        units = new ArrayList<>();
        adapter4.setUnits(units);
        initListener();
        setAdapter();
        getProvinceData();
        recyclerViews = new RecyclerView[]{recyclerView1,recyclerView2,recyclerView3,recyclerView4};
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                for (int i=0;i<recyclerViews.length;i++){
                    recyclerViews[i].setVisibility(View.GONE);
                }
                recyclerViews[position].setVisibility(View.VISIBLE);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        AddressPicker that = this;
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                that.dismiss();
            }
        });
        this.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                lp.alpha = 1f;
                activity.getWindow().setAttributes(lp);
            }
        });

    }
    private void setAdapter(){
        adapter1.setListener(listener1);
        adapter2.setListener(listener2);
        adapter3.setListener(listener3);
        adapter4.setListener(listener4);
        recyclerView1.setAdapter(adapter1);
        recyclerView2.setAdapter(adapter2);
        recyclerView3.setAdapter(adapter3);
        recyclerView4.setAdapter(adapter4);
    }
    private void initListener(){
        listener1 = new AddressPickerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (provinces.get(position).isSelect()){
                    return;
                }
                provinces.get(pIndex).setSelect(false);
                provinces.get(position).setSelect(true);
                pIndex = position;
                adapter1.notifyDataSetChanged();
                getCityData(provinces.get(pIndex).getId());
                tabLayout.getTabAt(1).select();
//                citys.get(cIndex).setSelect(false);
//                citys.clear();
//                citys.addAll(dataList.get(position).getCitys());
//                adapter2.notifyDataSetChanged();
//                areas.get(aIndex).setSelect(false);
//                areas.clear();
//                areas.addAll(dataList.get(position).getCitys().get(0).getAreas());
//                adapter3.notifyDataSetChanged();
//                units.get(uIndex).setSelect(false);
//                units.clear();
//                units.addAll(dataList.get(position).getCitys().get(0).getAreas().get(0).getUnits());
//                adapter4.notifyDataSetChanged();
            }
        };
        listener2 = new AddressPickerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (citys.get(position).isSelect()){
                    return;
                }
                citys.get(cIndex).setSelect(false);
                citys.get(position).setSelect(true);
                cIndex = position;
                adapter2.notifyDataSetChanged();
                getAreaData(citys.get(cIndex).getId());
                tabLayout.getTabAt(2).select();
//                areas.get(aIndex).setSelect(false);
//                areas.clear();
//                areas.addAll(dataList.get(position).getCitys().get(0).getAreas());
//                adapter3.notifyDataSetChanged();
//                units.get(uIndex).setSelect(false);
//                units.clear();
//                units.addAll(dataList.get(position).getCitys().get(0).getAreas().get(0).getUnits());
//                adapter4.notifyDataSetChanged();
            }
        };
        listener3 = new AddressPickerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (areas.get(position).isSelect()){
                    return;
                }
                areas.get(aIndex).setSelect(false);
                areas.get(position).setSelect(true);
                aIndex = position;
                adapter3.notifyDataSetChanged();
                getUnitData(areas.get(aIndex).getId());
                tabLayout.getTabAt(3).select();
//                units.get(uIndex).setSelect(false);
//                units.clear();
//                units.addAll(dataList.get(position).getCitys().get(0).getAreas().get(0).getUnits());
//                adapter4.notifyDataSetChanged();
            }
        };
        listener4 = new AddressPickerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (units.get(position).isSelect()){
                    return;
                }
                units.get(uIndex).setSelect(false);
                units.get(position).setSelect(true);
                uIndex = position;
                adapter4.notifyDataSetChanged();
                String des = provinces.get(pIndex).getName() + "-";
                des += citys.get(cIndex).getName() + "-";
                des += areas.get(aIndex).getName() + "-";
                des += units.get(uIndex).getName();
                listener.onPick(provinces.get(pIndex),citys.get(cIndex),areas.get(aIndex),units.get(uIndex));
                dismiss();
            }
        };
    }
    /**
     * 设置窗口的相关属性
     */
    @SuppressLint("InlinedApi")
    private void setPopupWindow() {
        this.setContentView(mPopView);// 设置View
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);// 设置弹出窗口的宽
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);// 设置弹出窗口的高
        this.setFocusable(true);// 设置弹出窗口可
        this.setAnimationStyle(R.style.popwindow_anim_bottom);// 设置动画
        this.setBackgroundDrawable(new BitmapDrawable());// 设置背景透明
        //this.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mPopView.setOnTouchListener(new View.OnTouchListener() {// 如果触摸位置在窗口外面则销毁
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                int height = mPopView.findViewById(R.id.id_pop_layout).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });


    }

    public void setDataList(List<ProvinceData> dataList) {
        this.dataList = dataList;
    }

    public void setListener(OnAddressPickListener listener) {
        this.listener = listener;
    }

    public interface OnAddressPickListener{
        void onPick(ProvinceData province,CityData city,AreaData ares,UnitData unit);
    }

    private void getProvinceData(){
        ShopApi.getInstance().service
                .getProvince(token)
                .compose(RxSchedulers.io_main())
                .subscribe(new Observer<BaseResult<List<ProvinceData>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResult<List<ProvinceData>> listBaseResult) {
                        if (listBaseResult.isError()){
                            T.show(listBaseResult.getMsg());
                        }else if (listBaseResult.getData() != null && listBaseResult.getData().size() > 0){
                            provinces.clear();
                            provinces.addAll(listBaseResult.getData());
                            //provinces.get(0).setSelect(true);
                            adapter1.notifyDataSetChanged();
                            pIndex = 0;
                            cIndex = 0;
                            aIndex = 0;
                            uIndex = 0;
                            getCityData(listBaseResult.getData().get(0).getId());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getCityData(String provinceId){
        Logger.d("省ID:"+provinceId);
        ShopApi.getInstance().service
                .getCitysByProvince(token,provinceId)
                .compose(RxSchedulers.io_main())
                .subscribe(new Observer<BaseResult<List<CityData>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResult<List<CityData>> listBaseResult) {
                        if (listBaseResult.isError()){
                            T.show(listBaseResult.getMsg());
                        }else if (listBaseResult.getData() != null && listBaseResult.getData().size() > 0){
                            citys.clear();
                            citys.addAll(listBaseResult.getData());
                            //citys.get(0).setSelect(true);
                            adapter2.notifyDataSetChanged();
                            cIndex = 0;
                            aIndex = 0;
                            uIndex = 0;
                            //tabLayout.getTabAt(1).select();
                            getAreaData(listBaseResult.getData().get(0).getId());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getAreaData(String cityId){
        ShopApi.getInstance().service
                .getAreasByCity(token,cityId)
                .compose(RxSchedulers.io_main())
                .subscribe(new Observer<BaseResult<List<AreaData>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResult<List<AreaData>> listBaseResult) {
                        if (listBaseResult.isError()){
                            T.show(listBaseResult.getMsg());
                        }else if (listBaseResult.getData() != null && listBaseResult.getData().size() > 0){
                            areas.clear();
                            areas.addAll(listBaseResult.getData());
                            //areas.get(0).setSelect(true);
                            adapter3.notifyDataSetChanged();
                            aIndex = 0;
                            uIndex = 0;
                            //tabLayout.getTabAt(2).select();
                            getUnitData(listBaseResult.getData().get(0).getId());
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getUnitData(String areaId){
        ShopApi.getInstance().service
                .getUnitsByArea(token,areaId)
                .compose(RxSchedulers.io_main())
                .subscribe(new Observer<BaseResult<List<UnitData>>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull BaseResult<List<UnitData>> listBaseResult) {
                        if (listBaseResult.isError()){
                            T.show(listBaseResult.getMsg());
                        }else if (listBaseResult.getData() != null && listBaseResult.getData().size() > 0){
                            units.clear();
                            units.addAll(listBaseResult.getData());
                            adapter4.notifyDataSetChanged();
                            uIndex = 0;
                            //tabLayout.getTabAt(3).select();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
